package com.hsxshop.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hsxshop.model.*;
import com.hsxshop.service.*;
import com.hsxshop.util.*;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangchongya on 17/7/12.
 */
@Controller
@RequestMapping(value = "/intention")
public class IntentionController {

    @Resource(name = "intentionService")
    private IntentionService intentionService;

    @Resource(name = "userService")
    private UserService userService;

    @Resource(name = "baseEntityService")
    private BaseEntityService baseEntityService;

    @RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String index(@RequestBody Map requestMap){
        Pagination pagination= PaginationTool.getPagination(requestMap);

        String phone=ParamConvertTool.getParamStr(requestMap,"phone");
        String beginTime=ParamConvertTool.getParamStr(requestMap,"beginTime");
        String endTime=ParamConvertTool.getParamStr(requestMap,"endTime");
        String whereStr="";
        if(null!=requestMap.get("state")){
            int state=ParamConvertTool.getParamInt(requestMap,"state");
            if(state!=-2) {
                whereStr = " and state=" + state;
            }
        }
        if(!"".equals(phone)){
            User whereU= userService.getEntity("from User where phone=?0",phone);
            if(null!=whereU){
                whereStr=" and userId="+whereU.getId();
            }else{
                return JsonTool.returnObjectJsonErrorMsg("该手机不存在");
            }

        }

        if(!"".equals(beginTime)){
            whereStr=" and createTime<"+beginTime;
        }
        if(!"".equals(endTime)){
            whereStr=" and createTime<"+endTime;
        }

        List<Intention> lists=intentionService.findByHQLWithPagination(pagination, SqlTool.returnSql("new Intention(id,userId,createTime,endTime,state,supplyId,demandId,storage,type,trace,remark,displayType)", "Intention", " where createTime<?0"+whereStr, "order by createTime desc"), DateTool.getStringDate());
        List intentions=new ArrayList();
        for (Intention intention: lists){
            Map map=new HashMap();
            String user_phone="--";
            if(intention.getUserId()!=0){
                //查找用户手机
                User u=userService.getEntity(intention.getUserId());
                String name="".equals(u.getName()) ? u.getNickname() : u.getName();
                if("".equals(name)){
                    user_phone=u.getPhone();
                }else{
                    user_phone=u.getPhone()+"("+name+")";
                }
            }
            intention.setUserPhone(user_phone);
        }
        return JsonTool.returnListJsonSuccess(lists, pagination);
    }
    @RequestMapping(value = "/detail",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String detail(@RequestBody Map requestMap){

        //查找意向订单
        Intention intention=intentionService.getEntity(ParamConvertTool.getParamInt(requestMap,"id"));

        Map map=new HashMap();
        if(null==intention){
            return JsonTool.returnObjectJsonErrorMsg("意向订单不存在");
        }
        String sqlMap="select phone,name,nickName from user where id=?0";
        Map userMap=baseEntityService.getMapByHQL(sqlMap,intention.getUserId());
        String content="";
        String traceTxt="";
        ObjectMapper mapper = new ObjectMapper();
        List<String> lists=new ArrayList<String>();
        if(!"".equals(intention.getTrace())){
            try {
                lists=(List<String>) mapper.readValue(intention.getTrace(),List.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        for (int i=0;i<lists.size();i++){
            traceTxt=traceTxt+i+"、"+lists.get(i)+"<br />";
        }

        if(intention.getType()==3){
            //撮合的话不显示客户信息
            content="开始时间："+intention.getCreateTime()+"<br />"+"过程："+traceTxt+"备注："+intention.getRemark()+"<br />";
        }else{
            //显示客户信息
            String userText="";
            if(null!=userMap){
                String name="".equals(ParamConvertTool.getParamStr(userMap,"name")) ? ParamConvertTool.getParamStr(userMap,"nickName") : ParamConvertTool.getParamStr(userMap,"name");
                userText="姓名："+name+"<br />"+"联系方式："+userMap.get("phone")+"<br />";
            }
            content=userText+"开始时间："+intention.getCreateTime()+"<br />"+"过程："+traceTxt+"备注："+intention.getRemark()+"<br />";
        }
        map.put("content",content);
        map.put("intention",intention);

        //查找sql语句
        String sqlSupply="select si.shipCode,si.seafoodName,si.sortTime,si.arrivalTime,si.arrivalDockName,si.townName,si.origin,si.storageTemp,si.packingDesc,si.remark,sd.weight,sd.specName,sd.price,user.name,user.nickName,user.phone from supply_info si inner join user on user.phone=si.phone inner join supply_details sd on si.id=sd.supplyId where si.id=?0";
        Map supplyMap= baseEntityService.getMapByHQL(sqlSupply,intention.getSupplyId());
        String supplyText="";
        if(null!=supplyMap){
            String shipCode=ParamConvertTool.getParamStr(supplyMap,"shipCode");
            String seafoodName=ParamConvertTool.getParamStr(supplyMap,"seafoodName");
            String sortTime=ParamConvertTool.getParamStr(supplyMap,"sortTime");
            String arrivalTime=ParamConvertTool.getParamStr(supplyMap,"arrivalTime");
            String arrivalDockName=ParamConvertTool.getParamStr(supplyMap,"arrivalDockName");
            String townName=ParamConvertTool.getParamStr(supplyMap,"townName");
            String origin=ParamConvertTool.getParamStr(supplyMap,"origin");
            String storageTemp=ParamConvertTool.getParamStr(supplyMap,"storageTemp");
            String packingDesc=ParamConvertTool.getParamStr(supplyMap,"packingDesc");
            String remark=ParamConvertTool.getParamStr(supplyMap,"remark");
            int weight=ParamConvertTool.getParamInt(supplyMap,"weight");
            String specName=ParamConvertTool.getParamStr(supplyMap,"specName");
            int price=ParamConvertTool.getParamInt(supplyMap,"price")/100;
            String name="".equals(ParamConvertTool.getParamStr(supplyMap,"name")) ? ParamConvertTool.getParamStr(supplyMap,"nickName") : ParamConvertTool.getParamStr(supplyMap,"name");
            String phone=ParamConvertTool.getParamStr(supplyMap,"phone");

            String shipCodeText="".equals(shipCode) ? "" : ("渔船号："+shipCode+"<br />");
            String seafoodNameText="".equals(seafoodName) ? "" : ("鱼类："+seafoodName+"<br />");
            String specNameText="规格："+specName+"<br />";
            String priceText="价格："+price+"元/斤"+"<br />";
            String weightText="重量："+weight+"斤"+"<br />";
            String sortTimeText="发布时间："+sortTime+"<br />";
            String arrivalTimeText=(intention.getStorage()==0 ? "截止时间：" : "到港时间：")+arrivalTime+"<br />";
            String placeText="交易地点："+townName+arrivalDockName;

            String originText=("".equals(origin) ? "" : ("<br />"+"产地："+origin));
            String storageTempText=("".equals(storageTemp) ? "" : ("<br />"+"存储温度："+storageTemp));
            String packingDescText=("".equals(packingDesc) ? "" : ("<br />"+"包装说明："+packingDesc));
            String remarkText=("".equals(remark) ? "" : ("<br />"+"备注："+remark));
            supplyText="姓名："+name+"<br />"+"联系方式："+phone+"<br />"+shipCodeText+seafoodNameText+specNameText+priceText+weightText+sortTimeText+arrivalTimeText+placeText+
                    originText+storageTempText+packingDescText+remarkText;
        }

        map.put("supply",supplyText);

        //查找求购
        String sqlDemand="select di.seafoodName,di.sortTime,di.demandTime,di.arrivalDockName,di.townName,di.remark,dd.weight,dd.specName,dd.price,user.name,user.nickName,user.phone FROM demand_info di inner join user on user.phone=di.phone inner join demand_details dd on di.id=dd.demandId where di.id=?0";
        Map demandMap= baseEntityService.getMapByHQL(sqlDemand,intention.getDemandId());
        String demandtext="";
        if(null!=demandMap){
            String seafoodName=ParamConvertTool.getParamStr(demandMap,"seafoodName");
            String sortTime=ParamConvertTool.getParamStr(demandMap,"sortTime");
            String demandTime=ParamConvertTool.getParamStr(demandMap,"demandTime");
            String arrivalDockName=ParamConvertTool.getParamStr(demandMap,"arrivalDockName");
            String townName=ParamConvertTool.getParamStr(demandMap,"townName");
            String remark=ParamConvertTool.getParamStr(demandMap,"remark");
            int weight=ParamConvertTool.getParamInt(demandMap,"weight");
            String specName=ParamConvertTool.getParamStr(demandMap,"specName");
            int price=ParamConvertTool.getParamInt(demandMap,"price")/100;
            String name=""==ParamConvertTool.getParamStr(demandMap,"name") ? ParamConvertTool.getParamStr(demandMap,"nickName") : ParamConvertTool.getParamStr(demandMap,"name");
            String phone=ParamConvertTool.getParamStr(demandMap,"phone");
            String seafoodNameText=""==seafoodName ? "" : ("鱼类："+seafoodName+"<br />");
            String specNameText="规格："+specName+"<br />";
            String priceText="价格："+price+"元/斤"+"<br />";
            String weightText="重量："+weight+"斤"+"<br />";
            String sortTimeText="发布时间："+sortTime+"<br />";
            String demandTimeText="截止时间："+demandTime+"<br />";
            String placeText="交易地点："+townName+arrivalDockName;
            String remarkText=""==remark ? "" : ("<br />"+"备注："+remark);
            demandtext="姓名："+name+"<br />"+"联系方式："+phone+"<br />"+seafoodNameText+specNameText+priceText+weightText+sortTimeText+demandTimeText+placeText+remarkText;
        }
        map.put("demand",demandtext);

        return JsonTool.returnObjectJsonSuccess(map);
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String edit(@RequestBody Map requestMap){

        int state=ParamConvertTool.getParamInt(requestMap,"state");
        if(state==0){
            return JsonTool.returnObjectJsonErrorMsg("状态不能设置为审核中");
        }
        //查找意向订单
        Intention intention=intentionService.getEntity(ParamConvertTool.getParamInt(requestMap,"id"));
        if(null==intention){
            return JsonTool.returnObjectJsonErrorMsg("意向订单不存在");
        }

        if(intention.getState()==2 || intention.getState()==3){
            return JsonTool.returnObjectJsonErrorMsg("交易成功的不允许修改状态！！");
        }

        List<String> lists=new ArrayList<String>();
        ObjectMapper mapper = new ObjectMapper();
        if(!"".equals(intention.getTrace())){
            try {
                lists=(List<String>) mapper.readValue(intention.getTrace(),List.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String stateText="";
        String endTime=DateTool.getStringDate();
        switch (state){
            case -1:
                stateText="客服在 "+endTime+" 审核失败";
                break;
            case 1:
                stateText="客服在 "+endTime+" 审核成功,交易员跟进中";
                break;
            case 2:
                stateText="在 "+endTime+" 交易成功";
                break;
            case 3:
                stateText="在 "+endTime+" 上传票据";
                break;
        }
        lists.add(stateText);

        String trace="";
        try {
            trace=mapper.writeValueAsString(lists);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String sql="update Intention set state=?0,trace=?1,endTime=?2 where id=?3";
        if(intentionService.execHQL(sql,state,trace,endTime,intention.getId())==1){
            return JsonTool.returnObjectJsonSuccess(null);
        }else{
            return JsonTool.returnObjectJsonError(null);
        }
    }

}
